$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'app/carousel/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
			{ label: '标题', name: 'title', index: 'title', width: 80 }, 			
			{ label: '图片', name: 'pic', index: 'pic', width: 80,formatter:function(value, options, row){
				return '<img width="50px" hieght="50px" src="'+value+'">';
			}  }, 			
		/*	{ label: '标记', name: 'flag', index: 'flag', width: 80 }, 		*/	
			{ label: '状态', name: 'invalid', index: 'invalid', width: 80,formatter: function(value, options, row){
				return value == 0 ? '无效' : '有效';
			} }, 			
			{ label: '描述', name: 'remark', index: 'remark', width: 80 }, 			
			{ label: '有效期开始', name: 'startdate', index: 'startdate', width: 80 }, 			
			{ label: '有效期结束', name: 'enddate', index: 'enddate', width: 80 }, 			
			{ label: '展现方式', name: 'type', index: 'type', width: 80,formatter: function(value, options, row){
				return value == 0 ? '图文商品' : '商品列表';
			}  }, 			
			{ label: '编码', name: 'code', index: 'code', width: 80 }			
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		carousel: {}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.carousel = {};
			vm.formatDate();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            vm.formatDate();
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
			var startdate =$('#startdate').data().datetimepicker.date;  
			var startdatetime = new Date(startdate);  
			vm.carousel.startdate = this.formatDateTime(startdatetime,'yyyy-MM-dd hh:mm:ss');
			
			var enddate =$('#enddate').data().datetimepicker.date;  
			var enddatetime = new Date(enddate);  
			vm.carousel.enddate = this.formatDateTime(enddatetime,'yyyy-MM-dd hh:mm:ss');
			
			var url = vm.carousel.id == null ? "app/carousel/save" : "app/carousel/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.carousel),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "app/carousel/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "app/carousel/info/"+id, function(r){
                vm.carousel = r.carousel;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
		formatDate:function(){
			$('#startdate,#enddate').datetimepicker({
		        weekStart: 1,
		        todayBtn:  1,
				autoclose: 1,
				todayHighlight: 1,
				startView: 2,
				forceParse: 0,
		        showMeridian: 1,
		        format: "yyyy-mm-dd hh:ii:ss",
		        language:  'zh-CN'
		    });
		},
		formatDateTime :function(date, fmt) {
		    if (/(y+)/.test(fmt)) {
		        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
		    }
		    let o = {
		        'M+': date.getMonth() + 1,
		        'd+': date.getDate(),
		        'h+': date.getHours(),
		        'm+': date.getMinutes(),
		        's+': date.getSeconds()
		    };
		    for (let k in o) {
		        if (new RegExp(`(${k})`).test(fmt)) {
		            let str = o[k] + '';
		            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length));
		        }
		    }
		    return fmt;
		},
		addPic:function(e){
			var files = e.target.files || e.dataTransfer.files;
            if (!files.length)return; 
			if(typeof FileReader==='undefined'){
                alert('您的浏览器不支持图片上传，请升级您的浏览器');
                return false;
            }
            var image = new Image();         
            var vm = this;
            var reader = new FileReader();
            reader.readAsDataURL(files[0]); 
            reader.onload =function(e){
            vm.carousel.pic=e.target.result;       
            };                 
		}
	}
});